﻿using Models;
using Models.RModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RedisHelper.Notify
{
    public class LatestLike
    {
        /// <summary>
        /// 获取最新点赞数
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public long GetLatestLikeCount(int uid)
        {
            using (RedisHelper rh = new RedisHelper())
            {
                return rh.GetDatabase(6).ListLength(StaticConfigRidesName.LatestLikes_List(uid));
            }
        }

        /// <summary>
        /// 插入最新点赞
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="r_LatestLikes"></param>
        /// <returns></returns>
        public bool InsertLastestLike(int uid, R_LatestLikes r_LatestLikes)
        {
            using (RedisHelper rh = new RedisHelper())
            {
                var data = rh.GetDatabase(6);
                //判断是否重复插入
                var list = data.ListRange(StaticConfigRidesName.LatestLikes_List(uid)).ToList();
                var judge = list.FirstOrDefault(u =>
                {
                    var info = JsonConvert.DeserializeObject<R_LatestLikes>(u);
                    if (info.UserId == r_LatestLikes.UserId && info.ArticleId == r_LatestLikes.ArticleId && info.CommentId == r_LatestLikes.CommentId)
                        return true;
                    return false;
                });
                if (judge.IsNull)
                {
                    if (data.ListRightPush(StaticConfigRidesName.LatestLikes_List(uid), JsonConvert.SerializeObject(r_LatestLikes)) != 0)
                        return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 查询最新点赞集合
        /// </summary>
        /// <returns></returns>
        public List<R_LatestLikes> GetLike(int uid)
        {
            List<R_LatestLikes> list = new List<R_LatestLikes>();
            using (RedisHelper rh = new RedisHelper())
            {
                var data = rh.GetDatabase(6);
                var dataList = data.ListRange(StaticConfigRidesName.LatestLikes_List(uid)).ToList();

                dataList.ForEach(u => list.Add(JsonConvert.DeserializeObject<R_LatestLikes>(u)));

                return list;
            }
        }

        /// <summary>
        /// 清空最新点赞
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelLike(int uid)
        {
            try
            {
                using (RedisHelper rh = new RedisHelper())
                {
                    rh.GetDatabase(6).KeyDelete(StaticConfigRidesName.LatestLikes_List(uid));
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
